package com.mhc.suzuki.controller.credit;

import com.mhc.haval.security.model.User;
import com.mhc.suzuki.bo.CreditQueryApplyBO;
import com.mhc.suzuki.bo.CustomerBO;
import com.mhc.suzuki.constant.AnnexGroupEnum;
import com.mhc.suzuki.constant.ErrorCodeEnum;
import com.mhc.suzuki.exception.SuzukiCommonException;
import com.mhc.suzuki.form.CreditCustomerForm;
import com.mhc.suzuki.form.CreditQueryForm;
import com.mhc.suzuki.form.CreditQueryListForm;
import com.mhc.suzuki.form.EditCreditForm;
import com.mhc.suzuki.service.CreditSerivce;
import com.mhc.suzuki.vo.CreditInfoVO;
import com.mhc.suzuki.vo.CreditListVO;
import com.subaru.common.entity.BizResult;
import com.subaru.common.query.PageResult;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 征信列表查询、征信结果录入、征信详情查询
 * Created by HMJ on 2017/8/16.
 */
@Slf4j
@RestController
@RequestMapping(value = "/credit")     // 通过这里配置使下面的映射都在/credit下，可去除
public class CreditController {

    @Autowired
    private CreditSerivce creditSerivce;

    /**
     * 获取查询征信列表
     * @param logedUser      登录人信息
     * @param creditQueryListForm    表单搜索内容
     * @return
     */
    @ApiOperation(value = "获取查询征信列表", httpMethod = "GET", notes = "根据查询条件获取征信列表")
    @RequestMapping(value = {"/list"}, method = RequestMethod.GET)
    public BizResult list(@AuthenticationPrincipal User logedUser, CreditQueryListForm creditQueryListForm) {
        BizResult result = new BizResult();
        try {
            CreditQueryApplyBO creditQueryApplyBO = new CreditQueryApplyBO();
            BeanUtils.copyProperties(creditQueryListForm, creditQueryApplyBO);
            if(logedUser.getBankId()!=null){
                log.info("该员工:{} 属于银行驻点员...", logedUser.getStaffName());
                PageResult<CreditQueryApplyBO> pageResult = creditSerivce.selectByCreidtList(creditQueryApplyBO,logedUser);
                List<CreditListVO> creditList = new ArrayList<>();
                /**将BO转化成VO**/
                for (CreditQueryApplyBO creditBO : pageResult.getResult()) {
                    CreditListVO creditListVO = new CreditListVO();
                    BeanUtils.copyProperties(creditBO, creditListVO);
                    creditList.add(creditListVO);
                }
                result.setData(creditList);                                      //结果
                result.setPageSize(creditQueryApplyBO.getPageSize());            //每页大小
                result.setPageNo(creditQueryApplyBO.getPageNo());                //页数
                result.setTotalCount(pageResult.getTotalCount());                //总条数
                result.setCode(ErrorCodeEnum.SUCCESS.getErrCode());
                result.setMessage(ErrorCodeEnum.SUCCESS.getErrMsg());
                result.setSuccess(true);
                log.info("获取征信列表成功...");
            }else {
                log.error("该员工:{} 不属于银行驻点员，无权限操作...", logedUser.getStaffName());
                return BizResult.create(ErrorCodeEnum.NO_AUTH.getErrCode(), ErrorCodeEnum.NO_AUTH.getErrMsg());
            }
        } catch (SuzukiCommonException e) {
            log.error("CreidtList SuzukiCommonException",e);
            return BizResult.create(e.getCode(),e.getMessage());
        }
        return result;
    }

    /**
     * 根据订单号获取征信结果详情
     * @param orderNo 订单号
     * @return
     */
    @ApiOperation(value = "获取征信结果详情", httpMethod = "GET", notes = "根据订单号获取征信列表详细信息")
    @RequestMapping(value = {"/look/{orderNo}"}, method = RequestMethod.GET)
    @ApiImplicitParam(name = "orderNo", value = "订单号", required = true, paramType = "path", dataType = "String")
    public BizResult look(@PathVariable String orderNo) {
        try {
            List<CreditQueryApplyBO> list = creditSerivce.queryByCreidtInfo(orderNo);
            /**将BO转化成VO**/
            List<CreditInfoVO> creditInfo = new ArrayList<>();
            for (CreditQueryApplyBO creditQueryApplyBO : list) {
                CreditInfoVO creditInfoVO = new CreditInfoVO();
                BeanUtils.copyProperties(creditQueryApplyBO, creditInfoVO);
                creditInfo.add(creditInfoVO);
            }
            /**将数据重新组装**/
            Map<String, Object> creditMap = new HashMap<>(64);
            List<CreditInfoVO> arrayList = new ArrayList<>();
            for (int i = 0; i < creditInfo.size(); i++) {
                CreditInfoVO creditInfoList = creditInfo.get(i);
                /**主贷人征信信息**/
                if (creditInfoList.getCustomerType().equals(AnnexGroupEnum.BUYER.getCode().toString())) {
                    creditMap.put("buyer", creditInfoList);
                }
                /**共同购车人征信信息**/
                if (creditInfoList.getCustomerType().equals(AnnexGroupEnum.COMMONBUYER.getCode().toString())) {
                    creditMap.put("commonBuyer", creditInfoList);
                }
                /**担保人征信信息**/
                if (creditInfoList.getCustomerType().equals(AnnexGroupEnum.SPONSOR.getCode().toString())) {
                    arrayList.add(creditInfoList);
                    creditMap.put("sponsor", arrayList);
                }
            }
            log.info("获取征信结果详情成功...");
            return BizResult.create(creditMap, ErrorCodeEnum.SUCCESS.getErrCode(), ErrorCodeEnum.SUCCESS.getErrMsg());
        } catch (SuzukiCommonException e) {
            log.error("CreidtLook SuzukiCommonException,订单号："+orderNo,e);
            return BizResult.create(e.getCode(),e.getMessage());
        }
    }

    /**
     * 征信结果录入
     *
     * @param creditQueryForm 征信录入表单信息
     * @return
     */
    @ApiOperation(value = "征信结果录入", httpMethod = "POST", notes = "征信结果录入")
    @RequestMapping(value = {"/creditEnter"}, method = RequestMethod.POST)
    @ApiImplicitParam(name = "creditQueryForm", value = "征信结果", required = false, paramType = "body", dataType = "CreditQueryForm")
    public BizResult creditEnter(@RequestBody CreditQueryForm creditQueryForm,@AuthenticationPrincipal User logedUser) {
        try {
            CreditQueryApplyBO creditQueryApplyBO = new CreditQueryApplyBO();
            BeanUtils.copyProperties(creditQueryForm, creditQueryApplyBO);
            Boolean insertFlag = creditSerivce.saveCreditResult(creditQueryApplyBO,logedUser);
            log.info("征信结果录入成功");
            return BizResult.create(insertFlag, ErrorCodeEnum.SUCCESS.getErrCode(), ErrorCodeEnum.SUCCESS.getErrMsg());
        } catch (SuzukiCommonException e) {
            log.error("CreditEnter SuzukiCommonException,订单号："+creditQueryForm.getOrderNo(),e);
            return BizResult.create(e.getCode(),e.getMessage());
        }catch (IOException e){
            log.error("CreditEnter SuzukiCommonException,订单号："+creditQueryForm.getOrderNo(),e);
            return BizResult.create(null,e.getMessage());
        }
    }


     /**
      * 征信修改
      * @param editCreditForm     修改信息
      * @return
      */
     @ApiOperation(value = "征信修改", httpMethod = "POST",notes = "征信修改")
     @RequestMapping(value = {"/updateCredit"}, method = RequestMethod.POST)
     @ApiImplicitParam(name = "editCreditForm", value = "征信结果", required = false,paramType = "body",dataType = "EditCreditForm")
     public BizResult updateCredit(@RequestBody EditCreditForm editCreditForm,@AuthenticationPrincipal User logedUser) {
         try {
             /**初始化购车人、共同购车人对象、担保人列表**/
             CustomerBO  buyerBO = new CustomerBO();             //购车人
             CustomerBO  commonBuyerBO = new CustomerBO();       //共同购车人
             List<CustomerBO> sponsorList = new ArrayList<>();   //担保人列表
             /**购车人**/
             CreditCustomerForm buyer = editCreditForm.getBuyer();
             BeanUtils.copyProperties(buyer,buyerBO);
             /**共同购车人**/
             if(editCreditForm.getCommonBuyer()!=null){
                 CreditCustomerForm commonBuyer = editCreditForm.getCommonBuyer();
                 BeanUtils.copyProperties(commonBuyer,commonBuyerBO);
             }
             /**担保人**/
             if(editCreditForm.getSponsor()!=null){
                 for(CreditCustomerForm creditCustomerForm:editCreditForm.getSponsor()){
                     CustomerBO customerBO = new CustomerBO();
                     BeanUtils.copyProperties(creditCustomerForm,customerBO);
                     sponsorList.add(customerBO);
                 }
             }
             boolean updateFlag = creditSerivce.updateCreditInfo(buyerBO,commonBuyerBO,sponsorList,logedUser);
             log.info("征信修改成功");
             return BizResult.create(updateFlag,ErrorCodeEnum.SUCCESS.getErrCode(),ErrorCodeEnum.SUCCESS.getErrMsg());
         }catch (SuzukiCommonException e){
             log.error("UpdateCredit SuzukiCommonException",e);
             return BizResult.create(e.getCode(),e.getMessage());
         }catch (IOException e){
             log.error("UpdateCredit SuzukiCommonException",e);
             return BizResult.create(null,e.getMessage());
         }
     }

}


